package edu.cmu.vlis.wassup.db;

import java.io.*;
import java.util.*;

import org.mybeans.editor.*;
import org.mybeans.factory.*;

public class Announcement_Tag_Dao {
	// Private table used to store user's address information
	private BeanTable<Announcement_Tag> eventTable;
	private BeanFactory<Announcement_Tag> eventFactory;
	
	private static void loadProperties(){
        Properties props = new Properties();
        try {
            props.load(new FileInputStream("src/properties"));
            System.getProperties().putAll(props);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

	// Constructor of Editor
	// The default is used to store records in MYSQL database
	// without JDBC connection information 
	public Announcement_Tag_Dao() {
			//loadProperties();
			BeanTable.useJDBC("com.mysql.jdbc.Driver", System.getProperty("org.mybeans.factory.jdbcURL")+"?user=root&password=wassup");
			// initialize table and bean factory
			AnnouncementDao ad = new AnnouncementDao();
			eventTable = BeanTable.getInstance(Announcement_Tag.class,"Announcement_Tag", ad.getFactory()); // Get event table
			createTable();
	}
	
	// Constructor of Editor
	// The default is used to store records in MYSQL database
	public Announcement_Tag_Dao(String URL) {
			// TODO Auto-generated method stub
			// Records are stored in MYSQL
			// clear the system property first
			System.clearProperty("org.mybeans.factory.csvDirectory");
			// Link to jdbc driver through mysql
			System.setProperty("org.mybeans.factory.jdbcDriver","com.mysql.jdbc.Driver");
			System.setProperty("org.mybeans.factory.jdbcURL","jdbc:mysql://"+URL+"/wassup");
	
			// Indicate username/password to the mysql database
			System.setProperty("org.mybeans.factory.user", "root" );
			System.setProperty("org.mybeans.factory.password", "wassup");
			
			// initialize table and bean factory
			AnnouncementDao ad = new AnnouncementDao();
			eventTable = BeanTable.getInstance(Announcement_Tag.class,"Announcement_Tag", ad.getFactory()); // Get event table
			createTable();
	}
	
	/** Create an mapping between announcements and interests 
	 * 1) if it already exists, keep the old one.
	 * 2) if it does not exist, create a new one.
	 * 
	 */
	public void createTable() {
		// Check whether the table has existed
		// If it is the case, delete the old table
		if (!eventTable.exists()) 
			// Create a new table
			eventTable.create("announce_id", "tag"); // Indicate primary key
		
		// get the bean factory to the table
		eventFactory = eventTable.getFactory();
	}
	
	// Call for bean editor
	public void createEditor() {
		BeanEditor<Announcement_Tag> editor = BeanEditor.getInstance(eventFactory);
		editor.start();
	}
	
	/** Insert a new tuple of announcement_interesting mappping into the beanTable
	 * Returns error message if creation fails.
	 * Otherwise return a null upon success.
	 * 
	 * @param announcement_id
	 * @param tags
	 * @throws RollbackException
	 */
	public void insert(Announcement announcement_id, String tags) throws RollbackException 
	{
		if (!Transaction.isActive())	// If the former transaction does not end normally
			Transaction.begin();	// Begin a new transaction
//		try {
			eventFactory.create(announcement_id, tags);
			Transaction.commit();
//		}
//		catch (Exception e) {
//			;
//		}
	}

	/** Lookup whether a typical event exists in the table
	 * Return Not Found if the events information is missing
	 * Otherwise return detailed information about event of a user
	 * 
	 * @param event_id
	 * @return
	 * @throws RollbackException
	 */
	public Announcement_Tag lookup(Announcement announcement_id, String tag) throws RollbackException {
		Announcement_Tag message = eventFactory.lookup(announcement_id, tag);
		// Looking up using primary key
		String result = "";
		if (message==null) {
			//throw new RollbackException("The tuple is not found!");
			return null;
		} 
		else {
			result+="SELECT: Message Id="+"; Announcement_id="+message.getAnnounce_id()+
				"; Tag="+message.getTag();
			result+=" \nin " + eventFactory.getBeanCount()+" results.";
		}
		System.out.println(result);
		
		return message;
	}
	
	
	/** Delete a tuple with primary key as composing of Announcement and Tag
	 * return null if no tuple is affected
	 * 
	 * @param event_id
	 * @return
	 */
	public Announcement_Tag delete(Announcement announcement_id, String tag) throws RollbackException {
		Announcement_Tag message = eventFactory.lookup(announcement_id, tag);
		// Looking up using primary key
		String result = "";
		if (message==null) {
			throw new RollbackException("The tuple is not found!");
		} 
		else {
			result+="DELETE: Message Id="+"; Announcement_id="+message.getAnnounce_id()+
				"; Tag="+message.getTag();
			result+=" \nin " + eventFactory.getBeanCount()+" results.";
			
			if (!Transaction.isActive())	// If the former transaction does not end normally
				Transaction.begin();	// Begin a new transaction
			
			eventFactory.delete(announcement_id, tag);
			
			Transaction.commit();
		}
		System.out.println(result);
		return message;
	}
	
	/**
	 * Get all the messages about a certain announcement
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public Announcement_Tag[] getTuplesFromAnnouncement(Announcement a) throws RollbackException {
		Announcement_Tag[] at = null;
		at = eventFactory.match(MatchArg.equals("announce_id",a));
		return at;
	}
	
	/**
	 * Get all the messages about a certain tag
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public Announcement[] getAnnouncementFromTag(String tag) throws RollbackException {
		Announcement_Tag[] at = null;
		at = eventFactory.match(MatchArg.equals("tag",tag));
		
		Announcement[] as = new Announcement[at.length];

		if (at.length>=1) {
			for (int i = 0; i<at.length; i++) {
				//as.add(at[i].getAnnounce_id());
				as[i] = at[i].getAnnounce_id();
			}
		}
		return as;
	}
	
	/**
	 * Get all the tags a certain user is interested in 
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public String[] getTagFromAnnouncement(Announcement a) throws RollbackException {
		Announcement_Tag[] uis = null;
		uis = eventFactory.match(MatchArg.equals("announce_id",a));
		
		String[] as = new String[uis.length];

		if (uis.length>=1) {
			for (int i = 0; i<uis.length; i++) {
				//as.add(uis[i].getTag());
				as[i] = uis[i].getTag();
			}
		}
		return as;
	}
	public static void main(String[] args) {
		loadProperties();
		Announcement_Tag_Dao edit = new Announcement_Tag_Dao();
		//edit.createEditor();
		//edit.insert(0,1);
		//event event = edit.lookup(1);
		//edit.upinsert(1,  "Celeberating VLIS", "All students");
		//edit.delete(2);
		
		//edit.getTable();
	}
}
